<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商ID" prop="supplierId">
        <el-input
          v-model="queryParams.supplierId"
          placeholder="请输入供应商ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="订单日期" prop="orderDate">
        <el-date-picker clearable
                        v-model="queryParams.orderDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择订单日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="true"
          @click="handleAdd"
          v-hasPermi="['supply:psorders:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supply:psorders:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supply:psorders:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supply:psorders:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="psordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="订单ID" align="center" prop="orderId"/>
      <el-table-column label="订单号" align="center" prop="orderNumber"/>
      <el-table-column label="供应商ID" align="center" prop="supplierId"/>
      <el-table-column label="订单金额" align="center" prop="orderAmount"/>
      <el-table-column label="支付方式" align="center" prop="paymentMethod"/>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="收货地址" align="center" prop="address" min-width="200">
        <template slot-scope="scope">
          <div class="address-info" v-if="scope.row.address">
            <!--            <el-tag size="small" :type="scope.row.userName === '默认地址' ? 'success' : 'primary'">-->
            <!--              {{ scope.row.userName || '地址标签' }}-->
            <!--            </el-tag>-->
            <div class="address-text">{{ scope.row.address }}</div>
          </div>
          <span v-else>暂无地址信息</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货时间" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.orderStatus == 1"
            size="mini"
            type="text"
            icon="el-icon-shopping-cart-full"
            @click="handlePay(scope.row)"
          >去支付
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['supply:psorders:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改供应商采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderNumber">
          <el-input v-model="form.orderNumber" placeholder="请输入订单号"/>
        </el-form-item>
        <el-form-item label="供应商ID" prop="supplierId">
          <el-input v-model="form.supplierId" placeholder="请输入供应商ID"/>
        </el-form-item>
        <el-form-item label="客户ID" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户ID"/>
        </el-form-item>
        <el-form-item label="订单金额" prop="orderAmount">
          <el-input v-model="form.orderAmount" placeholder="请输入订单金额"/>
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-input v-model="form.paymentMethod" placeholder="请输入支付方式"/>
        </el-form-item>
        <el-form-item label="订单日期" prop="orderDate">
          <el-date-picker clearable
                          v-model="form.orderDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择订单日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 支付对话框 -->
    <el-dialog
      title="选择支付方式"
      :visible.sync="payDialogVisible"
      width="400px"
      @close="handlePayClose">

      <el-skeleton :loading="loading" animated>
        <template #template>
          <el-skeleton-item variant="text" style="width: 30%"/>
          <el-skeleton-item variant="text"/>
          <el-skeleton-item variant="text" style="width: 60%"/>
        </template>

        <template #default>
          <div class="goods-details">
            <h3>商品明细（共 {{ orderProducts.length }} 项）</h3>
            <el-table :data="orderProducts" border size="mini">
              <el-table-column prop="name" label="商品名称" width="200"/>
              <el-table-column label="单价" width="120">
                <template #default="{row}">￥{{ row.unitPrice.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100"/>
              <el-table-column label="小计" width="120">
                <template #default="{row}">
                  ￥{{ (row.quantity * row.unitPrice).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>

            <div class="total-amount">
              订单总额：<span class="amount">￥{{
                orderProducts.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0).toFixed(2)
              }}</span>
            </div>
          </div>
        </template>
      </el-skeleton>

      <div style="text-align:center;">
        <el-radio-group v-model="selectedPayMethod">
          <el-radio label="微信支付" border>
            <i class="el-icon-success" style="color:#67C23A;"></i>
            微信支付
          </el-radio>
          <el-radio label="支付宝支付" border>
            <i class="el-icon-success" style="color:#409EFF;"></i>
            支付宝支付
          </el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmPay">立即支付</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择支付方式"
      :visible.sync="payDialogVisible1"
      width="400px"
      @close="handlePayClose">

      <el-skeleton :loading="loading" animated>
        <template #template>
          <el-skeleton-item variant="text" style="width: 30%"/>
          <el-skeleton-item variant="text"/>
          <el-skeleton-item variant="text" style="width: 60%"/>
        </template>

        <template #default>
          <div class="goods-details">
            <h3>商品明细（共 {{ orderProducts.length }} 项）</h3>
            <el-table :data="orderProducts" border size="mini">
              <el-table-column prop="name" label="商品名称" width="200"/>
              <el-table-column label="单价" width="120">
                <template #default="{row}">￥{{ row.unitPrice.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100"/>
              <el-table-column label="小计" width="120">
                <template #default="{row}">
                  ￥{{ (row.quantity * row.unitPrice).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>

            <div class="total-amount">
              订单总额：<span class="amount">￥{{
                orderProducts.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0).toFixed(2)
              }}</span>
            </div>
          </div>
        </template>
      </el-skeleton>

      <div style="text-align:center;">
        <el-radio-group v-model="selectedPayMethod">
          <el-radio label="微信支付" border>
            <i class="el-icon-success" style="color:#67C23A;"></i>
            微信支付
          </el-radio>
          <el-radio label="直接拿货" border>
            <i class="el-icon-success" style="color:#409EFF;"></i>
            直接拿货
          </el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="confirmPay">立即支付</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择支付方式"
      :visible.sync="payDialogVisible2"
      width="400px"
      @close="handlePayClose">

      <el-skeleton :loading="loading" animated>
        <template #template>
          <el-skeleton-item variant="text" style="width: 30%"/>
          <el-skeleton-item variant="text"/>
          <el-skeleton-item variant="text" style="width: 60%"/>
        </template>

        <template #default>
          <div class="goods-details">
            <h3>商品明细（共 {{ orderProducts.length }} 项）</h3>
            <el-table :data="orderProducts" border size="mini">
              <el-table-column prop="name" label="商品名称" width="200"/>
              <el-table-column label="单价" width="120">
                <template #default="{row}">￥{{ row.unitPrice.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100"/>
              <el-table-column label="小计" width="120">
                <template #default="{row}">
                  ￥{{ (row.quantity * row.unitPrice).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>

            <div class="total-amount">
              订单总额：<span class="amount">￥{{
                orderProducts.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0).toFixed(2)
              }}</span>
            </div>
          </div>
        </template>
      </el-skeleton>

      <div style="text-align:center;">
        <el-radio-group v-model="selectedPayMethod">
          <el-radio label="微信支付" border>
            <i class="el-icon-success" style="color:#67C23A;"></i>
            微信支付
          </el-radio>
          <el-radio label="银行转账" border>
            <i class="el-icon-success" style="color:#409EFF;"></i>
            银行转账
          </el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="confirmPay">立即支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPsordersById,
  listPsorders,
  getPsorders,
  delPsorders,
  addPsorders,
  updatePsorders
} from "@/api/supply/psorders";
import {getUserProfile} from "@/api/system/user";
import {getProdinfo} from "@/api/supply/prodinfo";
import request from "@/utils/request";

export default {
  name: "Psorders",
  dicts: ['order_status'],
  data() {
    return {
      user: {},
      payDialogVisible: false,
      payDialogVisible1: false,
      payDialogVisible2: false,
      selectedPayMethod: '微信支付',
      currentPayOrder: null, // 当前支付的订单
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商采购订单表格数据
      psordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        supplierId: null,
        customerId: null,
        orderDate: null,
        orderStatus: null
      },
      //订单商品信息
      orderProducts: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 是否是普通用户
      isRetail: false,
      // 是否是战略合作商
      isStratagem: false,
      // 是否是担保合作商
      isGuarantor: false,
      // 是否是管理员
      isAdmin: false,


    };
  },
  created() {

    this.getList();

  },
  methods: {

    /** 查询供应商采购订单列表 */
    getList() {
      this.loading = true;
      getUserProfile().then(response => {
        this.user = response.data;
        this.queryParams.customerId = this.user.userId;

        console.log('roles', response.data.roles);
        // 根据角色选择不同的弹窗支付方式
        response.data.roles.forEach((role, index) => {
          console.log('role.roleKey---' + index, role.roleKey);
          if (role.roleKey === 'purchaser-retail' || role.roleKey === 'purchaser-Audited' || role.roleKey === "supplier-retail") {
            this.isRetail = true;
          } else if (role.roleKey === 'purchaser-guarantor' || role.roleKey === "supplier-stratagem") {
            this.isGuarantor = true;
          } else if (role.roleKey === 'purchaser-stratagem' || role.roleKey === 'admin' || role.roleKey === "supplier-guarantor") {
            this.isStratagem = true;
          } else {
            //弹出提示
            this.$message({
              message: '您不是采购商，无法访问此页面',
              type: 'warning'
            });
          }
        });
        console.log('普通用户', this.isRetail);
        console.log("queryParams",this.queryParams)
        listPsorders(this.queryParams).then(response => {
          console.log(response.rows);
          const asv = this.mergeOrders(response.rows);
          this.psordersList = asv;
          console.log('psordersList', this.psordersList);
          this.total = response.total;
          this.loading = false;
        });
      });

    },

    //合并订单
    mergeOrders(orders) {
      const mergedMap = new Map();

      orders.forEach(order => {
        const key = order.orderNumber;
        if (mergedMap.has(key)) {
          // 合并金额
          const existing = mergedMap.get(key);
          existing.orderAmount = Number((existing.orderAmount + order.orderAmount).toFixed(2));

          // 合并商品和数量
          existing.products = [...existing.products, ...order.products];
          existing.quantities = [...existing.quantities, ...order.quantities];

          // 记录原始订单
          existing.originalOrders.push(order);
        } else {
          // 初始化合并项
          mergedMap.set(key, {
            ...order,
            orderAmount: Number(order.orderAmount.toFixed(2)),
            products: [...order.products],
            quantities: [...order.quantities],
            originalOrders: [order]
          });
        }
      });

      return Array.from(mergedMap.values());
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNumber: null,
        supplierId: null,
        customerId: null,
        orderAmount: null,
        paymentMethod: null,
        orderDate: null,
        orderStatus: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商采购订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getPsorders(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改供应商采购订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            // delete this.form.address
            // console.log("this.form", this.form);
            updatePsorders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPsorders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 获取所有原始订单ID
      const orderIds = row.originalOrders.map(o => o.orderId);


      this.$modal.confirm(`是否确认删除供应商采购订单编号为${row.orderNumber}的数据项？`).then(() => {
        delPsorders(orderIds.join(',')) // 根据后端接口支持批量删除
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supply/psorders/export', {
        ...this.queryParams
      }, `psorders_${new Date().getTime()}.xlsx`)
    },

    // 支付操作
    async handlePay(row) {
      try {
        this.currentPayOrder = row;
        console.log('row', row)
        if (this.isRetail === true) {
          this.payDialogVisible = true;
        }
        if (this.isStratagem === true) {
          this.payDialogVisible1 = true;
        }
        if (this.isGuarantor === true) {
          this.payDialogVisible2 = true;
        }

        this.loading = true;

        // 获取商品详细信息
        const productRequests = this.currentPayOrder.products.map(async (productId, index) => {
          const res = await getProdinfo(productId);
          console.log('res', res);

          return {
            productId: productId,
            name: res.data.name || '未知商品',
            quantity: this.currentPayOrder.quantities[index] || 0,
            unitPrice: res.data.unitPrice || 0.00
          };
        });

        this.orderProducts = await Promise.all(productRequests);
        console.log('orderProducts', this.orderProducts);

      } catch (error) {
        console.error('获取商品信息失败:', error);
        this.$message.error('商品信息加载失败');
      } finally {
        this.loading = false;
      }
    },

    confirmPay() {
      if (!this.selectedPayMethod) {
        this.$message.warning('请选择支付方式')
        return
      }

      // 计算订单总金额
      const totalAmount = this.orderProducts.reduce((sum, item) => sum + (item.quantity * item.unitPrice), 0);

      // 先检查钱包余额是否充足
      this.walletCheck(totalAmount).then(canPay => {
        if (!canPay) {
          this.$message.error('余额不足，请充值后再支付');
          return;
        }

        this.$confirm(`确认使用${this.selectedPayMethod}支付订单 ${this.currentPayOrder.orderNumber}？`, "支付确认", {
          confirmButtonText: "确认支付",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          const updateRequests = this.currentPayOrder.originalOrders.map(order => {
            delete order.address
            delete order.products
            delete order.quantities
            return updatePsorders({
              ...order,
              orderStatus: "0",
              paymentMethod: this.selectedPayMethod
            });
          });
          // 批量执行更新
          Promise.all(updateRequests)
            .then(() => {
              this.$modal.msgSuccess("支付成功");
              this.getList();
              this.payDialogVisible = false;
              this.payDialogVisible1 = false
              this.payDialogVisible2 = false
            })
            .catch(error => {
              console.error('部分订单支付失败', error);
              this.$message.error("支付失败: " + (error.msg || error.message));
            });
        })
      }).catch(error => {
        console.error('余额检查失败', error);
        this.$message.error("支付失败: " + (error.msg || error.message));
      });
    },

    // 检查钱包余额是否充足
    walletCheck(amount) {
      return new Promise((resolve, reject) => {
        request({
          url: '/supply/psorders/paycheck',
          method: 'get',
          params: { sum: amount }
        }).then(response => {
          if (response.code === 200) {
            resolve(true);
          } else {
            this.$message.warning(response.msg || '余额不足');
            resolve(false);
          }
        }).catch(error => {
          console.error('余额检查失败:', error);
          reject(error);
        });
      });
    },

    handlePayClose() {
      this.selectedPayMethod = '微信支付'
      this.currentPayOrder = null
    }
  }
};

</script>
<style scoped>
.goods-details {
  margin: 20px 0;
}

.total-amount {
  text-align: right;
  padding: 15px;
  font-size: 16px;
  border-top: 1px solid #ebeef5;
  margin-top: 10px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.address-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 5px;

  .el-tag {
    margin-bottom: 4px;
  }

  .address-text {
    font-size: 13px;
    color: #606266;
    line-height: 1.4;
    word-break: break-all;
    text-align: center;
  }
}
</style>
